from config import config
from services import service_mapper
from model import Info
from tools import store, http_utils

header = {
    "accept": "*/*",
    "accept-encoding": "identity;q=1, *;q=0",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,zh-TW;q=0.6,de;q=0.5,fr;q=0.4,ca;q=0.3,ga;q=0.2",
    "range": "bytes=0-",
    "sec-fetch-dest": "video",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-site": "cross-sit",
    "user-agent": config.user_agent
}


def download(info: Info):
    file = store.find_file(info.platform, info.filename)
    if file is not None:
        return make_stream_response(file, info.filename)

    service = service_mapper.get_service(info.platform)
    if info.extra is not None:
        service.complex_download(info)
    elif info.video != '':
        res = http_utils.get(url=info.video, header=service.download_header())
        if http_utils.is_error(res):
            return str(res)
        if len(res.content) < 1024:
            return "作品下载失败"
        store.save_file(info.platform, res, info.filename)
        res.close()
    else:
        store.save_image(info.platform, info.images, info.filename)

    file = store.find_file(info.platform, info.filename)
    if file is not None:
        return make_stream_response(file, info.filename)
    return 'download error'


def make_stream_response(file, filename):
    pass
